package com.acwer.oa.web.api.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.activiti.engine.task.TaskQuery;
import org.apache.bcel.generic.NEW;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.acwer.dao.bus.BusFileDao;
import com.acwer.dao.bus.ISqlMapper;
import com.acwer.dao.bus.TaskFormValDao;
import com.acwer.domain.bus.BusFile;
import com.acwer.domain.bus.TaskFormVal;
import com.acwer.domain.sys.RpnMsg;
import com.acwer.domain.sys.SysUser;
import com.acwer.oa.web.utils.TaskComplete;
import com.acwer.oa.web.utils.TaskComplete.FormProp;
import com.acwer.oa.wf.FlowUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 流程控制器
 * 
 * @author ZhaoJie
 *
 */
@RestController
@RequestMapping("wk-fw")
public class WorkFlowController extends BaseController {

	@Autowired
	RepositoryService repositoryService;
	@Autowired
	TaskService taskService;

	@Autowired
	RuntimeService runtimeService;

	@PostMapping("destroyProcDef")
	public RpnMsg destroyProcDef(@RequestBody Map<String, String> form) {
		RpnMsg msg = SUCCESS();
		Set<String> ids = new HashSet<String>(form.values());

		List<ProcessDefinition> defs = repositoryService.createProcessDefinitionQuery().processDefinitionIds(ids)
				.list();
		for (ProcessDefinition def : defs) {
			repositoryService.deleteDeployment(def.getDeploymentId(), true);
		}

		return msg;
	}

	/**
	 * 获取流程定义
	 * 
	 * @return
	 */
	@GetMapping("proc-list")
	public RpnMsg proceList(String act) {
		RpnMsg msg = SUCCESS();
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();

		if (!StringUtils.isEmpty(act)) {
			query = query.active();
		}
		query = query.orderByProcessDefinitionName().desc().orderByProcessDefinitionVersion().asc();

		List<ProcessDefinition> definitions = query.list();

		JSONArray array = new JSONArray();
		for (ProcessDefinition processDefinition : definitions) {
			JSONObject o = new JSONObject();

			o.put("id", processDefinition.getId());
			o.put("name", processDefinition.getName());
			o.put("category", processDefinition.getCategory());
			o.put("key", processDefinition.getKey());
			o.put("version", processDefinition.getVersion());
			o.put("deploymentId", processDefinition.getDeploymentId());
			o.put("category", processDefinition.getCategory());
			o.put("description", processDefinition.getDescription());
			o.put("resourceName", processDefinition.getResourceName());
			o.put("isSuspended", processDefinition.isSuspended());

			array.add(o);
		}
		msg.setData(array);

		return msg;
	}

	/**
	 * 发布流程
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@PostMapping("publish")
	public RpnMsg upload(@RequestParam("file") MultipartFile file) throws IOException {
		RpnMsg msg = SUCCESS();
		if (file.isEmpty()) {
			return msg;
		}
		Deployment deployment = repositoryService.createDeployment()
				.addInputStream(file.getOriginalFilename(), file.getInputStream()).deploy();
		msg.setData(deployment);
		return msg;
	}

	@Autowired
	BusFileDao fileDao;
	/**
	 * 任务附加上传
	 * 
	 * @param file
	 * @param taskId
	 * @param processInstanceId
	 * @param attachmentName
	 * @param attachmentDescription
	 * @throws IOException
	 */
	@Value("${spring.activiti.attach-path}")
	private String attachPath;
	
	/**
	 * 文件上传
	 * @param request
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@PostMapping("upload")
	public RpnMsg addAttachment(HttpServletRequest request,MultipartFile file) throws IOException {
		RpnMsg msg = SUCCESS();
		
		String fileName=file.getOriginalFilename();
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		
		fileName="/"+new SimpleDateFormat("yyyy/MM/dd").format(new Date())+"/";
		if(!Files.exists(Paths.get(attachPath+fileName))){
			Files.createDirectories(Paths.get(attachPath+fileName));
		}
		fileName+=UUID.randomUUID().toString()+suffixName;
		
		
		file.transferTo(Paths.get(attachPath+fileName));
		
		BusFile busFile=new BusFile();
		busFile.setCtime(new Date());
		
		String urlPrefixStr=FileUtils.getFile(attachPath).getName();
		
		busFile.setUrl("/"+urlPrefixStr+fileName);
		busFile.setSize(file.getSize());
		
		for (Entry<String, String[]> entry :request.getParameterMap().entrySet()) {
			try {
				Field field=busFile.getClass().getDeclaredField(entry.getKey());
				field.setAccessible(true);
				field.set(busFile, String.join(",", entry.getValue()));
				
			}catch (Exception e) {
				// TODO: handle exception
			}
		}
		fileDao.insert(busFile);
		msg.setData(busFile.getUrl());
		return msg;

	}
	
	/**
	 * 获取文件列表
	 * @param form
	 * @return
	 */
	@PostMapping("files")
	public RpnMsg files(@RequestBody Map<String, String> form){
		RpnMsg msg=SUCCESS();
		
		int page=1,limit=10;
		if(form.containsKey("page")){
			page=Integer.parseInt(form.get("page"));
		}
		if(form.containsKey("limit")){
			limit=Integer.parseInt(form.get("limit"));
		}
		
		QueryWrapper<BusFile> fileQuery=new QueryWrapper<BusFile>();
		String instid=form.get("instid");
		String taskid=form.get("taskid");
		
		if(!StringUtils.isEmpty(instid)){
			fileQuery.eq("instid", instid);
		}
		if(!StringUtils.isEmpty(taskid)){
			fileQuery.eq("taskid", taskid);
		}
		
		String bdate=form.get("bdate");
		String edate=form.get("edate");
		
		if(!StringUtils.isEmpty(bdate)){
			fileQuery.ge("ctime", new Date(bdate));
		}
		if(!StringUtils.isEmpty(edate)){
			fileQuery.le("ctime", new Date(edate));
		}
		String s=form.get("s");
		if(!StringUtils.isEmpty(s)){
			fileQuery.or().like("filename", s);
			fileQuery.or().like("filetype", s);
			fileQuery.or().like("filedesc", s);
//			like("filetype", "%"+s+"%").
//			like("filedesc", "%s"+s+"%");
		}
		fileQuery.orderByDesc("ctime");
		Page<BusFile> pg=new Page<BusFile>(page,limit);
		IPage<BusFile> rs=fileDao.selectPage(pg, fileQuery);
		
		JSONObject o=new JSONObject();
		o.put("total", rs.getTotal());
		o.put("ls", rs.getRecords());
		msg.setData(o);
		
		return msg;
	}

	/**
	 * 暂时或恢复流程定义
	 * 
	 * @param form
	 * @return
	 */
	@PostMapping("enableOrsuspended")
	public RpnMsg enableOrsuspended(@RequestBody Map<String, String> form) {
		RpnMsg msg = SUCCESS();
		String processDefinitionId = form.get("def");
		boolean f = repositoryService.isProcessDefinitionSuspended(processDefinitionId);
		if (!f)
			repositoryService.suspendProcessDefinitionById(processDefinitionId);
		else
			repositoryService.activateProcessDefinitionById(processDefinitionId);

		return msg;
	}

	@Autowired
	ISqlMapper sqlMapper;

	/**
	 * 开启一个流程实例
	 * 
	 * @param deploymentId
	 * @return
	 */
	@PostMapping("startProcessInstanceByDefId")
	public RpnMsg startProcessInstanceByKey(@RequestBody Map<String, String> form) {
		String key = form.get("key");
		String user = form.get("user");
		String title = form.get("title");

		RpnMsg msg = SUCCESS();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", user);

		ProcessInstance instance = runtimeService.startProcessInstanceById(key, map);

		// 设置实例标题
		if (StringUtils.isEmpty(title)) {
			ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
					.processDefinitionId(instance.getProcessDefinitionId()).singleResult();
			title = definition.getName();
		}
		runtimeService.setProcessInstanceName(instance.getId(), title);
		// formValDao.setStartUserId(user, instance.getId());
		// runtimeService.setVariable(instance.getSuperExecutionId(), "申请人",
		// user);
		String sql = "UPDATE ACT_HI_PROCINST set START_USER_ID_='" + user + "' WHERE ID_='" + instance.getId() + "'";
		sqlMapper.update(sql);

		JSONObject obj = new JSONObject();
		obj.put("DeploymentId", instance.getDeploymentId());
		obj.put("ActivityId", instance.getActivityId());
		obj.put("ProcessDefinitionId", instance.getProcessDefinitionId());
		obj.put("ProcessDefinitionKey", instance.getProcessDefinitionKey());
		obj.put("ProcessInstanceId", instance.getProcessInstanceId());
		obj.put("Id", instance.getId());
		Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();
		obj.put("taskId", task.getId());
//		taskService.delegateTask(task.getId(), user);
		msg.setData(obj);
		return msg;
	}

	/**
	 * 实例列表
	 * 
	 * @return
	 * @throws ParseException
	 */
	@PostMapping("inst-list")
	public RpnMsg instList(@RequestBody Map<String, String> form) throws ParseException {
		RpnMsg msg = SUCCESS();

		int page = 1, limit = 10;

		if (form.containsKey("page")) {
			page = Integer.parseInt(form.get("page"));
		}
		if (form.containsKey("limit")) {
			limit = Integer.parseInt(form.get("limit"));
		}

		HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();

		// 按流程名称
		Map<String, Object> parms = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(form.get("def"))) {
			query.processDefinitionName(form.get("def"));
		}

		// 按申请人查找
		if (!StringUtils.isEmpty(form.get("apply"))) {
			query.startedBy(form.get("apply"));
		}
		// 开始时间
		if (!StringUtils.isEmpty(form.get("bdate"))) {
			Date bdate = DateUtils.parseDate(form.get("bdate"), "yyyy-MM-dd", "yyyy-MM-dd hh:mm:ss");
			query.startedAfter(bdate);
		}
		if (!StringUtils.isEmpty(form.get("edate"))) {
			Date bdate = DateUtils.parseDate(form.get("edate"), "yyyy-MM-dd", "yyyy-MM-dd hh:mm:ss");
			query.startedBefore(bdate);
		}

		String s = form.get("s");
		if (!StringUtils.isEmpty(s)) {
			s = s.trim();
			query.processInstanceNameLike("%" + s + "%");
		}

		// 排序
		query = query.orderByProcessInstanceStartTime().desc();
		// TODO:其他查询条件

		// 分页总记录
		long total = query.count();

		List<HistoricProcessInstance> instances = query.listPage((page - 1) * limit, limit);

		JSONArray array = new JSONArray();

		for (HistoricProcessInstance instance : instances) {
			JSONObject o = new JSONObject();
			o.put("id", instance.getId());
			o.put("startTime", instance.getStartTime());
			o.put("name", instance.getName());
			o.put("processDefinitionId", instance.getProcessDefinitionId());
			o.put("processDefinitionName", instance.getProcessDefinitionName());
			o.put("startUserId", instance.getStartUserId());
			o.put("endDate", instance.getEndTime());
			o.put("durationInMillis", instance.getDurationInMillis());

			List<String> taskNames = historyService.createHistoricTaskInstanceQuery()
					.processInstanceId(instance.getId()).orderByHistoricTaskInstanceStartTime().asc().list().stream()
					.map(it -> it.getName()).collect(Collectors.toList());

			o.put("taskNames", String.join("->", taskNames));
			array.add(o);
		}
		JSONObject pageObj = new JSONObject();
		pageObj.put("total", total);
		pageObj.put("ls", array);
		msg.setData(pageObj);

		return msg;
	}

	/**
	 * 所有任务列表
	 * 
	 * @return
	 */
	@PostMapping("task-list")
	public RpnMsg taskList(@RequestBody Map<String, String> form) {
		RpnMsg msg = SUCCESS();

		HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery();

		String user = form.get("user");
		// 分页
		int page = 1, limit = 10;
		// 默认10条
		if (form.containsKey("limit")) {
			limit = Integer.parseInt(form.get("limit"));
		}
		if (form.containsKey("page")) {
			page = Integer.parseInt(form.get("page"));
		}

		// TODO:添加条件
		if (!StringUtils.isEmpty(user)) {
			query = query.or().taskAssignee(user).taskCandidateUser(user).endOr();
		}
		String instid = form.get("instid");
		if (!StringUtils.isEmpty(instid)) {
			query = query.processInstanceId(form.get("instid"));
		}

		// 分页
		// 满足条件的记录数
		long total = query.count();
		// 按任务开始时间排序
		query = query.orderByTaskCreateTime().asc();

		List<HistoricTaskInstance> tasks = query.listPage((page - 1) * limit, limit);

		QueryWrapper<TaskFormVal> fromVal = new QueryWrapper<TaskFormVal>();
		fromVal.eq("instid", instid);
		List<TaskFormVal> formVals = formValDao.selectList(fromVal);
		JSONArray array = new JSONArray();
		for (HistoricTaskInstance task : tasks) {
			JSONObject o = task2json(task);
			// 结束时间
			o.put("endDate", task.getEndTime());

			Map<String, String> map = new HashMap<String, String>();
			List<TaskFormVal> taskFormVals = formVals.stream().filter(it -> it.getTaskid().equals(task.getId()))
					.collect(Collectors.toList());
			taskFormVals.forEach(it -> {
				map.put(it.getName(), it.getVal());
			});
			o.put("vars", map);
			array.add(o);
		}

		JSONObject rs = new JSONObject();
		rs.put("total", total);
		rs.put("ls", array);
		msg.setData(rs);

		return msg;
	}

	/**
	 * 我的待办事宜
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping("mytodo")
	public RpnMsg mytodo(@RequestBody Map<String, String> form) {
		System.out.println(form);
		RpnMsg msg = SUCCESS();
		TaskQuery query = taskService.createTaskQuery();
		String s = form.get("s");
		int page = 1, limit = 10;
		if (form.containsKey("page")) {
			page = Integer.parseInt(form.get("page"));
		}
		if (form.containsKey("limit")) {
			limit = Integer.parseInt(form.get("limit"));
		}
		String user=form.get("user");
		if(!StringUtils.isEmpty(user)){
			query.taskCandidateOrAssigned(user);
			//query.taskOwner(owner)
		}
		if (!StringUtils.isEmpty(s)) {
			query.or().taskNameLike("%" + s + "%").processDefinitionNameLike("%" + s + "%").endOr();
		}
		List<Task> tasks = query.orderByTaskCreateTime().desc().listPage((page - 1) * limit, limit);
		long total = query.count();
		JSONArray array = new JSONArray();
		for (Task task : tasks) {

			JSONObject o = task2json(task);
			array.add(o);
		}

		JSONObject p = new JSONObject();
		p.put("total", total);
		p.put("ls", array);
		msg.setData(p);
		return msg;
	}

	private JSONObject task2json(TaskInfo task) {
		JSONObject o = new JSONObject();
		o.put("id", task.getId());
		o.put("name", task.getName());
		o.put("assignee", task.getAssignee());
		o.put("createTime", task.getCreateTime());
		o.put("processInstanceId", task.getProcessInstanceId());
		HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult();
		o.put("processDefinitionId", task.getProcessDefinitionId());
		o.put("instName", instance.getName());
		try {
			List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
			String idens = String.join(",",
					identityLinks.stream().map(it -> it.getUserId()).collect(Collectors.toList()));
			String grps = String.join(",",
					identityLinks.stream().map(it -> it.getGroupId()).collect(Collectors.toList()));
			o.put("candidateUsers", idens);
			o.put("candidateGroups ", grps);
		} catch (Exception e) {
			// TODO: handle exception
		}
		String startUser = historyService.createHistoricProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult().getStartUserId();

		o.put("startUser", startUser);

		ProcessDefinition def = repositoryService.createProcessDefinitionQuery()
				.processDefinitionId(task.getProcessDefinitionId()).singleResult();

		JSONObject taskDef = new JSONObject();
		taskDef.put("id", def.getId());
		taskDef.put("name", def.getName());
		taskDef.put("key", def.getKey());
		taskDef.put("Description", def.getDescription());
		o.put("def", taskDef);
		return o;
	}

	// @Autowired
	// FormPropertyDao formDao;
	/**
	 * 通过任务ID获取 以用于编辑
	 * 
	 * @param taskId
	 * @return
	 */
	@GetMapping("form")
	public RpnMsg form(
			// String defid,
			String taskid
	// @RequestParam(defaultValue="") String category
	) {
		RpnMsg msg = SUCCESS();
		Task task = taskService.createTaskQuery().taskId(taskid).singleResult();

		// String user=
		// historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult().getStartUserId();
		// System.out.println(user);
		//
		//
		JSONObject o = new JSONObject();
		JSONObject ts = new JSONObject();
		ts.put("name", task.getName());
		ts.put("assignee", task.getAssignee());
		ts.put("instid", task.getProcessInstanceId());
		o.put("task", ts);

		UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
				.getFlowElement(task.getTaskDefinitionKey());
		List<org.activiti.bpmn.model.FormProperty> formProperties = userTask.getFormProperties();
		o.put("form", formProperties);
		msg.setData(o);

		return msg;
	}

	@Autowired
	TaskFormValDao formValDao;

	/**
	 * 提交任务
	 * 
	 * @param taskComplete
	 * @return
	 */
	@PostMapping("taskComplete")
	public RpnMsg taskComplete(@RequestBody TaskComplete taskComplete) {
		RpnMsg msg = SUCCESS();
		try {
			int order = 0;
			List<FormProp> formProps = taskComplete.getForm();
			Map<String, Object> map = new HashMap<String, Object>();
			taskComplete.getForm().add(new FormProp() {
				{
					setId("处理人");
					setName("处理人");
					setVal(taskComplete.getUserId());
				}
			});
			taskComplete.getForm().forEach(it -> {
				map.put(it.getId(), it.getVal());
			});
			Date date = new Date();
			taskService.complete(taskComplete.getTaskId(), map);
			List<TaskFormVal> formVals = formProps.stream().map((it) -> {
				TaskFormVal val = new TaskFormVal();
				val.setTaskid(taskComplete.getTaskId());
				val.setOrdr(formProps.indexOf(it) + 1);
				val.setUserid(taskComplete.getUserId());
				val.setTaskname(taskComplete.getTaskName());
				val.setName(it.getId());
				val.setVal(it.getVal());
				val.setInstid(taskComplete.getInstid());
				val.setCtime(date);
				return val;
			}).collect(Collectors.toList());

			for (TaskFormVal taskFormVal : formVals) {
				formValDao.insert(taskFormVal);
			}

		} catch (Exception e) {
			msg = FAIL();
			msg.setMsg(e.getMessage());
		}
		return msg;
	}

	@Autowired
	HistoryService historyService;

	/**
	 * 历史任务信息
	 * 
	 * @param instid
	 *            流程实例id
	 * @return
	 */
	@GetMapping("h2t")
	public RpnMsg history2task(String instid) {
		RpnMsg msg = SUCCESS();

		QueryWrapper<TaskFormVal> valQuery = new QueryWrapper<TaskFormVal>();
		valQuery.eq("instid", instid);
		valQuery.orderByDesc("ctime");
		List<TaskFormVal> taskFormVals = formValDao.selectList(valQuery);

		// Map<String, Integer> map=new HashMap<String, Integer>();
		//
		// List<HistoricTaskInstance>
		// list=historyService.createHistoricTaskInstanceQuery().
		// processInstanceId(instid).
		// orderByHistoricTaskInstanceStartTime().asc().list();
		//
		// JSONArray array=new JSONArray();
		//
		// for (HistoricTaskInstance task : list) {
		// JSONObject t=new JSONObject();
		// t.put("id", task.getId());
		// t.put("name", task.getName());
		// t.put("assignee", task.getAssignee());
		// t.put("beginDate", task.getCreateTime());
		// t.put("endDate", task.getEndTime());
		// t.put("dueDate", task.getDueDate());
		// t.put("owner", task.getOwner());
		//
		// List<HistoricVariableInstance>
		// vars=historyService.createHistoricVariableInstanceQuery().
		// taskId(task.getId()).list();
		// JSONArray varJson=new JSONArray();
		// for (HistoricVariableInstance var : vars) {
		// JSONObject varObj=new JSONObject();
		// varObj.put("varId", var.getId());
		// varObj.put("varName", var.getVariableName());
		// varObj.put("varValue", var.getValue());
		// varObj.put("varCreateTime", var.getCreateTime());
		// varObj.put("varTypeName", var.getVariableTypeName());
		// if(map.containsKey(var.getVariableName())){
		// continue;
		// }
		// map.put(var.getVariableName(), 1);
		// varJson.add(varObj);
		// }
		// t.put("vars", varJson);
		// array.add(0, t);
		// }
		msg.setData(taskFormVals);
		return msg;
	}

	@GetMapping("test")
	public RpnMsg Test() {
		RpnMsg msg = SUCCESS();

		List<Task> list = taskService.createTaskQuery().processDefinitionKey("myProcess_1").taskCandidateUser("pansir")
				.list();
		System.out.println(list);
		return msg;
	}

	@Autowired
	FlowUtils flowUtils;

	/**
	 * 生成实时流程图
	 * 
	 * @param response
	 * @param instIdOrDefId
	 *            流程实例ID或流程定义ID，流程实例ID有高亮显示图片
	 * @throws Exception
	 */
	@RequestMapping(value = "img/{instIdOrDefId}", method = RequestMethod.GET)
	// HttpServletResponse response,@PathVariable("id")String id
	public RpnMsg img(HttpServletResponse response, @PathVariable("instIdOrDefId") String instIdOrDefId)
			throws Exception {
		InputStream input = flowUtils.getProcessDiagram(instIdOrDefId);
		ServletOutputStream output = response.getOutputStream();
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		IOUtils.copy(input, outputStream);
		// response.setContentType("image/png");
		// IOUtils.copy(input, output);
		RpnMsg msg = SUCCESS();
		String str = new String(outputStream.toByteArray(), "utf-8");
		msg.setData(str);
		return msg;
		// response.setContentType("application/octet-stream");

	}

}
